﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using TravelWallet.Types;
using System.Collections.ObjectModel;
using WindowsPhoneRecipes;
namespace TravelWallet
{
    public enum Mode
    {
        ADD, EDIT
    }
    public partial class AddProgram : PhoneApplicationPage
    {
        private Mode mode;
        private long itemID;
        private bool inReducedNameMode = false;

        
        private bool hasBeenVisited = false;

        public AddProgram()
        {
            InitializeComponent();
           // this.Loaded += new RoutedEventHandler(AddProgram_Loaded);
            this.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(AddProgram_BackKeyPress);
        }

        void AddProgram_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            WalletItem existingItem = DataContext as WalletItem;
            if (existingItem == null || existingItem.ID == 0)
            {
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
            else
            {
                string param = string.Format("itemId={0}", existingItem.ID);
                NavigationService.Navigate(new Uri("/ProgramDetails.xaml?" + param, UriKind.Relative));
            }
        }

        void AddProgram_Loaded(object sender, RoutedEventArgs e)
        {
            
            this.lp_Category.DataContext = App.ViewModel.CategoryNames;
            this.lp_Category.ItemsSource = App.ViewModel.CategoryNames;
            
            WalletItem existingItem = DataContext as WalletItem;

            if (existingItem != null)
            {

                if (existingItem.Category == ProgramCategory.Airlines)
                {
                    lp_Category.SelectedIndex = 0;
                }
                else if (existingItem.Category == ProgramCategory.CarRentals)
                {
                    lp_Category.SelectedIndex = 2;
                }
                else if (existingItem.Category == ProgramCategory.Hotels)
                {
                    lp_Category.SelectedIndex = 1;
                }
                //lp_Category.IsEnabled = false;
                /*
                if (!string.IsNullOrEmpty(existingItem.Program.Name) && !string.IsNullOrEmpty(existingItem.Program.ProgramName))
                {
                    //this.lp_Name.SelectionChanged -= lp_Name_SelectionChanged;
                    //this.lp_ProgramName.SelectionChanged -= lp_ProgramName_SelectionChanged;

                    lp_Name.ItemsSource = new List<string>() { existingItem.Program.Name};
                    lp_ProgramName.ItemsSource = new List<string>() { existingItem.Program.ProgramName };

                    //this.lp_Name.SelectionChanged += lp_Name_SelectionChanged;
                    //this.lp_ProgramName.SelectionChanged += lp_ProgramName_SelectionChanged;
                }*/
            }

             /*
            else { 
            
                 string category = "";
                 if (NavigationContext.QueryString.TryGetValue("category", out category))
                 {

                     if (category == "Airlines")
                     {
                         lp_Category.SelectedIndex = 0;
                     }
                     else if (category == "Hotels")
                     {
                         lp_Category.SelectedIndex = 1;
                     }
                     else
                     {
                         lp_Category.SelectedIndex = 2;
                     }

                 }
            }      
             */

        }

        private int GetProgramNameIndex(string programName)
        {
            int index = 0;
            foreach (string pName in lp_ProgramName.Items)
            {
                if (pName == programName)
                {
                    break;
                }
                index++;
            }
            return index;
        }

        private int GetNameIndex(string name)
        {
            int index = 0;
            foreach (string pName in lp_Name.Items)
            {
                if (pName == name)
                {
                    break;
                }
                index++;
            }
            return index;
        }


        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string mode = "";
            string itemId = "";
            string category = "";

            //if (hasBeenVisited)
            //{
            //    NavigationService.GoBack();
            //}

            //hasBeenVisited = true;

            if (NonLinearNavigationService.Instance.IsRecursiveBackNavigation == true)
            {
                return;
            }


            if (NavigationContext.QueryString.TryGetValue("mode", out mode))
            {
                NavigationContext.QueryString.TryGetValue("category", out category);
                if (mode.ToLower() == "add")
                {
                    this.mode = Mode.ADD;
                    WalletItem newItem = new WalletItem();
                    this.DataContext = newItem;
                    this.PageTitle.Text = "Add a Program";

                    ProgramCategory programCategory = (ProgramCategory)Enum.Parse(typeof(ProgramCategory), category, true);
                    newItem.Category = programCategory;

                }
                else
                {
                    if (NavigationContext.QueryString.TryGetValue("itemId", out itemId))
                    {
                        itemID = Convert.ToInt64(itemId);
                        this.mode = Mode.EDIT;
                        WalletItem existingItem = App.ViewModel.GetWalletItem(itemID);
                        DataContext = existingItem;
                        this.PageTitle.Text = "Edit Program";

                        lp_Category.IsEnabled = false;

                        lp_Name.ItemsSource = new List<string>() { existingItem.Program.Name };
                        lp_ProgramName.ItemsSource = new List<string>() { existingItem.Program.ProgramName };
                    }
                    else
                    {
                        throw new Exception(string.Format("AddProgram.OnNavigatedTo: Cannot find ID parameter for edit mode"));
                    }
                }
            }
            else
            {
                //return from a picker selection
                string selectionName;
                string selectedItem;
                string itemID;
                

                if (NavigationContext.QueryString.TryGetValue("category", out category) &&
                    NavigationContext.QueryString.TryGetValue("itemID", out itemID) &&
                    NavigationContext.QueryString.TryGetValue("selectionName", out selectionName) &&
                    NavigationContext.QueryString.TryGetValue("selectedItem", out selectedItem)
                    )
                {
                    selectedItem = Uri.UnescapeDataString(selectedItem);
                    long l_ID = Convert.ToInt64(itemID);
                    if (l_ID == default(long))
                    {
                        this.mode = Mode.ADD;
                        this.PageTitle.Text = "Add a Program";
                    }
                    else
                    {
                        this.mode = Mode.EDIT;

                        lp_Category.IsEnabled = false;

                        this.PageTitle.Text = "Edit Program";
                    }

                    WalletItem existingItem = App.ViewModel.GetWalletItem(Convert.ToInt64(l_ID));
                    if (existingItem == null)
                    {
                        existingItem = new WalletItem();
                        ProgramCategory programCategory = (ProgramCategory)Enum.Parse(typeof(ProgramCategory), category, true);
                        existingItem.Category = programCategory;
                       

                    }
                    this.DataContext = existingItem;

                    if (selectionName == "programname")
                    {
                        lp_ProgramName.ItemsSource = new List<string>() { selectedItem };

                        if (existingItem.Category == ProgramCategory.Airlines)
                        {
                            ProgramName_Changed(selectedItem, App.ViewModel.AirlineName);
                        }
                        else if (existingItem.Category == ProgramCategory.Hotels)
                        {
                            ProgramName_Changed(selectedItem, App.ViewModel.HotelNames);
                        }
                        else
                        {
                            ProgramName_Changed(selectedItem, App.ViewModel.RentalNames);
                        }
                    }
                    else if (selectionName == "name")
                    {
                        lp_Name.ItemsSource = new List<string>() { selectedItem };
                        if (existingItem.Category == ProgramCategory.Airlines)
                        {
                            Name_Changed(selectedItem, App.ViewModel.AirlineProgramNames);
                        }
                        else if (existingItem.Category == ProgramCategory.Hotels)
                        {
                            Name_Changed(selectedItem, App.ViewModel.HotelProgramNames);
                        }
                        else
                        {
                            Name_Changed(selectedItem, App.ViewModel.CarRentalProgramNames);
                        }
                    }
                }
            }



        }


        private void RefreshControl()
        {
            if (mode == Mode.ADD)
            {
                this.sp_Item.DataContext = new WalletItem();
            }
            else
            {
                WalletItem existingItem = App.ViewModel.GetWalletItem(itemID);
                this.sp_Item.DataContext = existingItem;
            }
        }

        private void b_Save_Click(object sender, EventArgs e)
        {   
            WalletItem item = DataContext as WalletItem;

            if (lp_Name.SelectedItem == null || lp_ProgramName.SelectedItem == null)
            {
                if (MessageBox.Show("A program name is required to save.", "Incomplete", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                {
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                }
            }
            else
            {
                ProgramCategory category = (ProgramCategory)Enum.Parse(typeof(ProgramCategory), lp_Category.SelectedItem.ToString().Replace(" ", ""), true);
                item.Category = category;

                Program program = App.ViewModel.GetProgramByName(lp_Name.SelectedItem.ToString());
                program.SelectedProgram = lp_ProgramName.SelectedItem.ToString();
                item.Program = program;

                item.Number = tb_Number.Text;

                if (mode == Mode.ADD)
                {
                    if (App.ViewModel.WalletItemsCount() >= 5)
                    {
                        if (!App.isTrialMode)
                        {
                            App.ViewModel.AddItemToWallet(item);
                            string param = "category=" + item.Category;
                            NavigationService.Navigate(new Uri("/MainPage.xaml?" + param, UriKind.Relative));
                        }
                        else
                        {
                            NavigationService.Navigate(new Uri("/BuyPage.xaml", UriKind.Relative));
                        }
                    }
                    else
                    {
                        App.ViewModel.AddItemToWallet(item);
                        string param = "category=" + item.Category;
                        NavigationService.Navigate(new Uri("/MainPage.xaml?" + param, UriKind.Relative));
                    }
                }
                else
                {
                    App.ViewModel.EditItemInWallet(item);
                    string param = string.Format("itemId={0}", item.ID);
                    NavigationService.Navigate(new Uri("/ProgramDetails.xaml?" + param, UriKind.Relative));
                }
            }
        }


        private void b_Cancel_Click(object sender, EventArgs e)
        {
            if (this.mode == Mode.ADD)
            {
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
            else
            {
                WalletItem existingItem = DataContext as WalletItem;
                string param = string.Format("itemId={0}", existingItem.ID);
                NavigationService.Navigate(new Uri("/ProfileDetails.xaml?"+param, UriKind.Relative));
            }
        }

        private void lp_Category_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //WalletItem newItem = new WalletItem();
            //this.DataContext = newItem;

            //put this if block in for WP8.0 port
            if (this.lp_Category.SelectedIndex != -1)
            {
                ProgramCategory category;
                category = GetSelectedCategory();

                if (category == ProgramCategory.Hotels)
                {
                    lp_Name.Visibility = System.Windows.Visibility.Collapsed;
                    lbl_Name.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    lbl_Name.Visibility = System.Windows.Visibility.Visible;
                    lp_Name.Visibility = System.Windows.Visibility.Visible;
                }
                // PopulateListPickersBasedOnCategory(category);
                // this.lp_Name.SelectedIndex = 1;
            }
        }

        private ProgramCategory GetSelectedCategory()
        {
            ProgramCategory category;
            string newCategory = lp_Category.SelectedItem.ToString();
            newCategory = newCategory.Replace(" ", "");


            category = (ProgramCategory)Enum.Parse(typeof(ProgramCategory), newCategory, true);
            return category;
        }

        //private void PopulateListPickersBasedOnCategory(ProgramCategory category)
        //{
        //    this.lp_Name.SelectionChanged -= lp_Name_SelectionChanged;
        //    this.lp_ProgramName.SelectionChanged -= lp_ProgramName_SelectionChanged;

        //    if (category == ProgramCategory.Airlines)
        //    {

        //        this.lp_Name.DataContext = App.ViewModel.AirlineName;
        //        this.lp_Name.ItemsSource = App.ViewModel.AirlineName;

        //        this.lp_ProgramName.DataContext = App.ViewModel.AirlineProgramNames.OrderBy(s => s) ;
        //        this.lp_ProgramName.ItemsSource = App.ViewModel.AirlineProgramNames.OrderBy(s => s);


        //    }
        //    else if (category == ProgramCategory.CarRentals)
        //    {
        //        this.lp_Name.DataContext = App.ViewModel.RentalNames;
        //        this.lp_Name.ItemsSource = App.ViewModel.RentalNames;

        //        this.lp_ProgramName.DataContext = App.ViewModel.CarRentalProgramNames.OrderBy(s => s); 
        //        this.lp_ProgramName.ItemsSource = App.ViewModel.CarRentalProgramNames.OrderBy(s => s); 
        //    }
        //    else
        //    {
        //        this.lp_Name.DataContext = App.ViewModel.HotelNames;
        //        this.lp_Name.ItemsSource = App.ViewModel.HotelNames;

        //        this.lp_ProgramName.DataContext = App.ViewModel.HotelProgramNames.OrderBy(s => s);
        //        this.lp_ProgramName.ItemsSource = App.ViewModel.HotelProgramNames.OrderBy(s => s);
        //    }



        //    this.lp_Name.SelectionChanged += lp_Name_SelectionChanged;
        //    this.lp_ProgramName.SelectionChanged += lp_ProgramName_SelectionChanged;

            
        //}

        private void Name_Changed(string newName, ObservableCollection<string> programNames)
        {
            if (lp_Name.SelectedItem != null)
            {
                string selection = newName;

                Program program = App.ViewModel.GetProgramByName(selection);
                lp_ProgramName.ItemsSource = new List<string>() { program.ProgramName};
                
                /*
                if (inReducedNameMode == true)
                {
                    PopulateListPickersBasedOnCategory(GetSelectedCategory());
                    inReducedNameMode = false;
                }
                 * */
                //  this.tb_ProgramName.Text = program.ProgramName;
            }
        }

        private void lp_Name_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (inReducedNameMode == true)
            {
                inReducedNameMode = false;
                string selectedItem = lp_Name.SelectedItem.ToString();

                lp_Name.ItemsSource = new List<string>() { selectedItem };
                lp_Name.MouseLeftButtonUp += lp_Name_MouseLeftButtonUp;
            }
        }
        //private void lp_Name_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    this.lp_ProgramName.SelectionChanged -= lp_ProgramName_SelectionChanged;
        //    if (lp_Name.SelectedItem != null && lp_ProgramName.ItemsSource != null)
        //    {
        //        string selection = lp_Name.SelectedItem.ToString();

        //        Program program = App.ViewModel.GetProgramByName(selection);
        //        int index = 0;

        //        foreach (string p in lp_ProgramName.ItemsSource)
        //        {
        //            if (p == program.ProgramName)
        //            {
        //                break;
        //            }
        //            index++;
        //        }

        //        this.lp_ProgramName.SelectedIndex = index;
        //        if (inReducedNameMode == true)
        //        {
        //            PopulateListPickersBasedOnCategory(GetSelectedCategory());
        //            inReducedNameMode = false;
        //        }
        //        //  this.tb_ProgramName.Text = program.ProgramName;
        //    }
        //    this.lp_ProgramName.SelectionChanged += lp_ProgramName_SelectionChanged;
        //}

        private void ProgramName_Changed(string newProgramName, ObservableCollection<string> names)
        {
            string selection = newProgramName;
            List<Program> programs = App.ViewModel.GetProgramsByProgramName(selection);

            if (programs.Count() > 1)
            {
                lp_Name.MouseLeftButtonUp -= lp_Name_MouseLeftButtonUp;
                lp_Name.ItemsSource = from p in programs
                                      select p.Name;

                lp_Name.DataContext = lp_Name.ItemsSource;
                inReducedNameMode = true;
            }
            else
            {
                inReducedNameMode = false;
                lp_Name.ItemsSource = new List<string>() { programs[0].Name };
            }
        }

        //private void lp_ProgramName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    this.lp_Name.SelectionChanged -= lp_Name_SelectionChanged;
        //    if (lp_ProgramName != null && lp_Name.ItemsSource != null)
        //    {
        //        string selection = lp_ProgramName.SelectedItem.ToString();
        //        List<Program> programs = App.ViewModel.GetProgramsByProgramName(selection);

        //        if (programs.Count() > 1)
        //        {

        //            lp_Name.ItemsSource = from p in programs
        //                                  select p.Name;

        //            lp_Name.DataContext = lp_Name.ItemsSource;
        //            inReducedNameMode = true;
        //        }
        //        else
        //        {
        //            inReducedNameMode = false;
        //            PopulateListPickersBasedOnCategory(GetSelectedCategory());
        //            int index = 0;
        //            foreach (string p in lp_Name.ItemsSource)
        //            {
        //                if (p == programs[0].Name)
        //                {
        //                    break;
        //                }
        //                index++;
        //            }
        //            lp_Name.SelectedIndex = index;
        //        }

        //    }
        //    this.lp_Name.SelectionChanged += lp_Name_SelectionChanged;

        //}


        private void lp_Name_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            WalletItem existingItem = DataContext as WalletItem;

            ProgramCategory lp_selectedCategory = new ProgramCategory();

            if (this.lp_Category.SelectedIndex == 0)
            {
                lp_selectedCategory = ProgramCategory.Airlines;
            }
            else if (this.lp_Category.SelectedIndex == 1)
            {
                lp_selectedCategory = ProgramCategory.Hotels;
            }
            else
            {
                lp_selectedCategory = ProgramCategory.CarRentals;
            }

            string createQueryString = ListSelectionPage.CreateQueryString(existingItem.ID, lp_selectedCategory, "name");
            NavigationService.Navigate(new Uri("/ListSelectionPage.xaml?"+createQueryString, UriKind.Relative));
        }

        private void lp_ProgramName_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            WalletItem existingItem = DataContext as WalletItem;

            ProgramCategory lp_selectedCategory = new ProgramCategory();

            if (this.lp_Category.SelectedIndex == 0)
            {
                lp_selectedCategory = ProgramCategory.Airlines;
            }
            else if (this.lp_Category.SelectedIndex == 1)
            {
                lp_selectedCategory = ProgramCategory.Hotels;
            }
            else
            {
                lp_selectedCategory = ProgramCategory.CarRentals;
            }

            string createQueryString = ListSelectionPage.CreateQueryString(existingItem.ID, lp_selectedCategory, "programname");
            NavigationService.Navigate(new Uri("/ListSelectionPage.xaml?" + createQueryString, UriKind.Relative));
        }

      

    }
}